//
//  JianbianView.m
//  danpin
//
//  Created by chuangjia on 14/12/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "JianbianView.h"

@implementation JianbianView

//[UIColor colorWithRed:0.967 green:0.967 blue:0.967 alpha:1]
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    NSArray *colors = [NSArray arrayWithObjects:
 
                       [UIColor colorWithRed:0.999 green:0.999 blue:0.999 alpha:1.0],

                       [UIColor colorWithRed:0.967 green:0.967 blue:0.967 alpha:1.0],

                       nil];

    [self _drawGradientColor:context

                        rect:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)
 
                     options:kCGGradientDrawsAfterEndLocation

                      colors:colors];

    CGContextStrokePath(context);// 描线,即绘制形状

    
    
    CGContextFillPath(context);// 填充形状内的颜色
}


/**
 02
 * 绘制背景色渐变的矩形，p_colors渐变颜色设置，集合中存储UIColor对象（创建Color时一定用三原色来创建）
 03
 **/

- (void)_drawGradientColor:(CGContextRef)p_context
rect:(CGRect)p_clipRect
options:(CGGradientDrawingOptions)p_options
colors:(NSArray *)p_colors {
    CGContextSaveGState(p_context);// 保持住现在的context
    CGContextClipToRect(p_context, p_clipRect);// 截取对应的context
    int colorCount = p_colors.count;
    int numOfComponents = 4;
    CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
    CGFloat colorComponents[colorCount * numOfComponents];
    for (int i = 0; i < colorCount; i++) {
        UIColor *color = p_colors[i];
        CGColorRef temcolorRef = color.CGColor;
        const CGFloat *components = CGColorGetComponents(temcolorRef);
        for (int j = 0; j < numOfComponents; ++j) {
            colorComponents[i * numOfComponents + j] = components[j];
        }
    }
    CGGradientRef gradient =  CGGradientCreateWithColorComponents(rgb, colorComponents, NULL, colorCount);
    CGColorSpaceRelease(rgb);
    CGPoint startPoint = p_clipRect.origin;
    CGPoint endPoint = CGPointMake(CGRectGetMinX(p_clipRect), CGRectGetMaxY(p_clipRect));
    CGContextDrawLinearGradient(p_context, gradient, startPoint, endPoint, p_options);
    CGGradientRelease(gradient);
    CGContextRestoreGState(p_context);// 恢复到之前的context
}


@end
